package cn.bytecollege.admin.controller;

import cn.bytecollege.admin.service.CategoryService;
import cn.bytecollege.admin.service.CuisineService;
import cn.bytecollege.common.entity.Cuisine;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "CategoryDeleteController", value = "/admin/categoryDelete")
public class CategoryDeleteController extends HttpServlet {
    private CategoryService categoryService=null;
    private CuisineService cuisineService=null;

    public CategoryDeleteController(){
        categoryService=new CategoryService();
        cuisineService=new CuisineService();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg=null;
        //1.获取请求参数
        String id=request.getParameter("id");
        Integer categoryId=Integer.valueOf(id);
        //2.判断该分类底下有没有菜品，所有要用CuisineService
        List<Cuisine>list=cuisineService.findByCategoryId(categoryId);
        if(list.size()>0){
            msg="该分类下有菜品，请先删除该菜品";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(request.getContextPath()+"/admin/categoryList").forward(request,response);
            return;
        }
        categoryService.deleteById(categoryId);
        //重定向
        response.sendRedirect(request.getContextPath()+"/admin/categoryList");
    }
}
